package com.asktgapp.user.activity;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.asktgapp.R;
import com.asktgapp.application.MyApplication;
import com.asktgapp.eventbus.WebEvent;
import com.asktgapp.modulebase.common.util.LogUtil;
import com.asktgapp.modulebase.common.util.PreferencesUtil;
import com.asktgapp.modulebase.common.util.Util;
import com.asktgapp.utils.NetworkUtils;
import com.sobot.chat.SobotApi;
import com.sobot.chat.api.model.Information;
import com.umeng.analytics.MobclickAgent;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.Map;


public class NewWebActivity extends Activity {

    private WebView baseWebView;
    private TextView title, back, myToolbarShare, messageNum, llMessageNum, tvRelease;
    public Toolbar toolbar;
    private RelativeLayout rlKF;
    private RelativeLayout llKF;
    private LinearLayout bottomKF;
    private String id = "";
    private int source;//0 home 1 正常 2 shop

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_web);
        EventBus.getDefault().register(this);
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        title = (TextView) findViewById(R.id.toolbar_title);
        back = (TextView) findViewById(R.id.tv_back);
        messageNum = (TextView) findViewById(R.id.messageNum);
        llMessageNum = (TextView) findViewById(R.id.llMessageNum);
        myToolbarShare = (TextView) findViewById(R.id.myToolbarShare);
        tvRelease = (TextView) findViewById(R.id.tvRelease);
        rlKF = (RelativeLayout) findViewById(R.id.rlKF);
        llKF = (RelativeLayout) findViewById(R.id.llKF);
        bottomKF = (LinearLayout) findViewById(R.id.bottomKF);
        source = getIntent().getIntExtra("source", 1);
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (source == 0) {
                    NewWebActivity.start(NewWebActivity.this, "http://shop.jg969.com:90/client/index", "找配件", 1);
                }
                onBackPressed();
            }
        });
        myToolbarShare.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //改为分享功能了
                Intent intent = new Intent(NewWebActivity.this, ShareActivity.class);
                intent.putExtra("type", 5);
                intent.putExtra("id", id);
                startActivity(intent);
            }
        });
        title.setSingleLine(true);
        title.setEllipsize(TextUtils.TruncateAt.END);
        toolbar.setVisibility(View.VISIBLE);

//        bindingView.progressBar.setMax(100);
        final String titelText = getIntent().getStringExtra("title");
        title.setText(titelText);
        String url = getIntent().getStringExtra("url");
        LogUtil.LogE("weburl", url);
        baseWebView = findViewById(R.id.baseWebView);


        if (url != null) {

            if (url.toLowerCase().contains("client/orderlist")) {
                String userId = PreferencesUtil.getString(this, PreferencesUtil.USER_ID);
                url = "http://shop.jg969.com:90/client/orderlist?id=" + userId;
                //url = url + "?id=" + userId;
            }


            baseWebView.loadUrl(url);
            if (url.contains("client/detail")) {
                Map<String, String> urlMap = NetworkUtils.urlSplit(url);
                if (urlMap.get("id") != null) {
                    id = urlMap.get("id");
                }

            } else if (url.contains("client/orderlist") || url.contains("client/orderdetail")) {
                llKF.setVisibility(View.GONE);
                rlKF.setVisibility(View.GONE);
                bottomKF.setVisibility(View.GONE);

                llMessageNum.setVisibility(View.GONE);
                if (url.contains("client/orderdetail")) {
                    rlKF.setVisibility(View.GONE);
                    myToolbarShare.setVisibility(View.INVISIBLE);
                } else {
                    tvRelease.setVisibility(View.VISIBLE);
                    myToolbarShare.setVisibility(View.GONE);

                    tvRelease.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            baseWebView.reload();
                        }
                    });
                }


            }
        }

        if (TextUtils.isEmpty(titelText)) {
            baseWebView.setWebViewClient(new WebViewClient() {
                @Override
                public void onPageFinished(WebView view, String url) {
                    super.onPageFinished(view, url);
                    String t = view.getTitle();
                    if (!TextUtils.isEmpty(t)) {
                        title.setText(t);
                    }
                }

                @Override
                public boolean shouldOverrideUrlLoading(WebView view, String url) {
                    if (url.startsWith("weixin://wap/pay?")) {
                        //如果return false  就会先提示找不到页面，然后跳转微信
                        Intent intent = new Intent();
                        intent.setAction(Intent.ACTION_VIEW);
                        intent.setData(Uri.parse(url));
                        try {
                            startActivity(intent);
                            finish();
                        } catch (Exception e) {
                            new AlertDialog.Builder(NewWebActivity.this)
                                    .setMessage("未检测到微信客户端，请安装后重试。")
                                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {

                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            finish();
                                        }
                                    }).show();
                        }

                        return true;
                    } else if (url.startsWith("alipays:") || url.startsWith("alipay")) {
                        try {
                            startActivity(new Intent("android.intent.action.VIEW", Uri.parse(url)));
                            finish();
                        } catch (Exception e) {
                            new AlertDialog.Builder(NewWebActivity.this)
                                    .setMessage("未检测到支付宝客户端，请安装后重试。")
                                    .setPositiveButton("立即安装", new DialogInterface.OnClickListener() {

                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            Uri alipayUrl = Uri.parse("https://d.alipay.com");
                                            startActivity(new Intent("android.intent.action.VIEW", alipayUrl));
                                            finish();
                                        }
                                    }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    finish();
                                }
                            }).show();
                        }

                        return true;
                    }
                    // ------- 处理结束 -------

//                    if (!(url.startsWith("http") || url.startsWith("https"))) {
//                        return true;
//                    }
                    return false;
                }

                @Override
                public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                    handler.proceed();
                }


            });
        }

        rlKF.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Information info = new Information();
                info.setAppkey("9d6b46705cd648b9bf1b66be4a9438bf");  //分配给App的的密钥
                if (!Util.isEmpty(PreferencesUtil.getString(MyApplication.getInstance(), PreferencesUtil.USER_ID))) {
                    info.setUid(PreferencesUtil.getString(MyApplication.getInstance(), PreferencesUtil.USER_ID));
//用户昵称，选填
//                    info.setUname(PreferencesUtil.getString(MyApplication.getInstance(), PreferencesUtil.KEY_NAME));
//                    info.setRealname(PreferencesUtil.getString(MyApplication.getInstance(), PreferencesUtil.KEY_NAME));
//用户电话，选填
                    info.setTel(PreferencesUtil.getString(MyApplication.getInstance(), PreferencesUtil.KEY_PHONE));
                }
                SobotApi.startSobotChat(getBaseContext(), info);
            }
        });
        bottomKF.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Information info = new Information();
                info.setAppkey("9d6b46705cd648b9bf1b66be4a9438bf");  //分配给App的的密钥
                if (!Util.isEmpty(PreferencesUtil.getString(MyApplication.getInstance(), PreferencesUtil.USER_ID))) {
                    info.setUid(PreferencesUtil.getString(MyApplication.getInstance(), PreferencesUtil.USER_ID));
//用户昵称，选填
//                    info.setUname(PreferencesUtil.getString(MyApplication.getInstance(), PreferencesUtil.KEY_NAME));
//                    info.setRealname(PreferencesUtil.getString(MyApplication.getInstance(), PreferencesUtil.KEY_NAME));
//用户电话，选填
                    info.setTel(PreferencesUtil.getString(MyApplication.getInstance(), PreferencesUtil.KEY_PHONE));
                }
                SobotApi.startSobotChat(getBaseContext(), info);
            }
        });
    }

    public static void start(Context mContext, String url, String title) {
        Intent intent = new Intent(mContext, NewWebActivity.class);
        intent.putExtra("url", url);
        intent.putExtra("title", title);
        intent.putExtra("source", 1);
        mContext.startActivity(intent);
    }

    public static void start(Context mContext, String url, String title, int source) {
        Intent intent = new Intent(mContext, NewWebActivity.class);
        intent.putExtra("url", url);
        intent.putExtra("title", title);
        intent.putExtra("source", source);
        mContext.startActivity(intent);
    }


    @Override
    public void onBackPressed() {
        if (baseWebView.canGoBack()) {
            baseWebView.goBack();

        } else {
            super.onBackPressed();
        }
    }

    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (source == 0) {
                NewWebActivity.start(NewWebActivity.this, "http://shop.jg969.com:90/client/index", "找配件", 1);
            }
            finish();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onDestroy() {
        if (baseWebView != null) {
            baseWebView.loadDataWithBaseURL(null, "", "text/html", "utf-8", null);
            baseWebView.clearHistory();
            ((ViewGroup) baseWebView.getParent()).removeView(baseWebView);
            baseWebView.destroy();
        }
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }


    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
        baseWebView.clearHistory();
        baseWebView.reload();

        if (SobotApi.getUnreadMsg(this, PreferencesUtil.getString(MyApplication.getInstance(), PreferencesUtil.USER_ID)) > 0) {
            messageNum.setVisibility(View.VISIBLE);
            llMessageNum.setVisibility(View.VISIBLE);
            if (SobotApi.getUnreadMsg(this, PreferencesUtil.getString(MyApplication.getInstance(), PreferencesUtil.USER_ID)) > 99) {
                messageNum.setText("99");
                llMessageNum.setText("99");
            } else {
                messageNum.setText(String.valueOf(SobotApi.getUnreadMsg(this, PreferencesUtil.getString(MyApplication.getInstance(), PreferencesUtil.USER_ID))));
                llMessageNum.setText(String.valueOf(SobotApi.getUnreadMsg(this, PreferencesUtil.getString(MyApplication.getInstance(), PreferencesUtil.USER_ID))));
            }
        } else {
            messageNum.setVisibility(View.GONE);
            llMessageNum.setVisibility(View.GONE);

        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void hasNewMsg(WebEvent event) {
        if (SobotApi.getUnreadMsg(MyApplication.getInstance(), PreferencesUtil.getString(MyApplication.getInstance(), PreferencesUtil.USER_ID)) > 0) {
            messageNum.setVisibility(View.VISIBLE);
            llMessageNum.setVisibility(View.VISIBLE);
            if (SobotApi.getUnreadMsg(MyApplication.getInstance(), PreferencesUtil.getString(MyApplication.getInstance(), PreferencesUtil.USER_ID)) > 99) {
                messageNum.setText("99");
                llMessageNum.setText("99");
            } else {
                messageNum.setText(String.valueOf(SobotApi.getUnreadMsg(MyApplication.getInstance(), PreferencesUtil.getString(MyApplication.getInstance(), PreferencesUtil.USER_ID))));
                llMessageNum.setText(String.valueOf(SobotApi.getUnreadMsg(MyApplication.getInstance(), PreferencesUtil.getString(MyApplication.getInstance(), PreferencesUtil.USER_ID))));
            }
        } else {
            messageNum.setVisibility(View.GONE);
            llMessageNum.setVisibility(View.GONE);
        }
    }
}
